import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:image_picker/image_picker.dart';
import '../../common/style/extension_util.dart';
import '../../user_data.dart';
import '../style/app_style.dart';
import '../widght/app_loading_widget.dart';
import '../widght/dailog/confirm_widget.dart';
import '../widght/permission_widget.dart';
import '../widght/rectangle_checkBox.dart';
import '../widght/textfiled_widget.dart';
import '../widght/webView_widget.dart';

import 'package:permission_handler/permission_handler.dart';
import 'package:device_info_plus/device_info_plus.dart';

abstract class WidgetUtil {
  static showDialog(String? title, String? content, VoidCallback onConfirmation,
      {bool? onlyOne,
      String? okText,
      VoidCallback? onCancel,
      TextAlign? textAlign,
      bool? clickMaskDismiss,
      String? cancelText,
      ConfirmStyle? style}) {
    SmartDialog.show(
        builder: (_) {
          return ConfirmWidget(
            title: title ?? "",
            content: content ?? "",
            textAlign: textAlign ?? TextAlign.center,
            onConfirmation: onConfirmation,
            onCancel: onCancel,
            onlySure: onlyOne ?? true,
            okText: okText ?? "确定",
            cancelText: cancelText,
            style: style ?? ConfirmStyle.style1(),
          );
        },
        clickMaskDismiss: clickMaskDismiss);
  }

  static showBottomSheet(String? title, String? content, VoidCallback onConfirmation,
      {bool? onlyOne,
        String? okText,
        VoidCallback? onCancel,
        TextAlign? textAlign,
        bool? clickMaskDismiss,
        String? cancelText,
        ConfirmStyle? style}) {
    SmartDialog.show(
      alignment: Alignment.bottomCenter,
        builder: (_) {
          return BottomDialog(
            title: title ?? "",
            content: content ?? "",
            textAlign: textAlign ?? TextAlign.left,
            onConfirmation: onConfirmation,
            onCancel: onCancel,
            onlySure: onlyOne ?? true,
            okText: okText ?? "confirm".tr,
            cancelText: cancelText,
            style: style ?? ConfirmStyle.style1(),
          );
        },
        clickMaskDismiss: clickMaskDismiss);
  }

  static showLoading() {
    SmartDialog.showLoading(
        msg: "", builder: (context) => const AppLoadingWidget());
  }

  static Widget checkBox(bool value, String title,
      {Function(bool?)? onTap, bool? isRadio = false, TextStyle? textStyle}) {
    return Row(
      children: [
        RectangleCheckBox(
          //自定义矩形的checkbox
          size: 30.w,
          // checkedColor: Colors.orange,
          checkedWidget: Icon(
            Icons.check_box_outline_blank,
            color: AppColor.primaryColor,
            size: 12.w,
          ),
          uncheckedWidget: Icon(
            Icons.check_box_outlined,
            color: AppColor.primaryColor,
            size: 12.w,
          ),
          isChecked: value,
          checkedColor: Colors.transparent,
          borderColor: Colors.transparent,
          uncheckedColor: Colors.transparent,
          disabledColor: Colors.transparent,
          onTap: (newValue) {
            onTap?.call(!value);
          },
        ),
        SizedBox(
          width: 3,
        ),
        Text(
          title,
          style: textStyle ?? AppStyle.textStyle,
        ).addExpand()
      ],
    ).addGestureTap(() {
      onTap?.call(!value);
    });
  }

  static Widget getSearchBar(
      {TextEditingController? controller,
      FormFieldSetter<String>? onSubmitted,
      ValueChanged<String>? onChanged,
      Color? bgColor,
      String hintText = "search",
      EdgeInsetsGeometry? padding,
      bool? autofocus,
      bool? enabled,
      GestureTapCallback? onTap,
      TextFormFieldWidgetType? type,
         bool? showArrowIcon,
        Key? key,
        double? height, VoidCallback? onEditingComplete
      }) {

    if(Platform.isWindows || Platform.isMacOS){
      height ??= 44.h;
    }else{
      height ??= 32.h;
    }
    return TextFormFieldWidget(
      key: key,
      autofocus: autofocus,
      controller: controller,
      enabled: enabled ?? true,
      hintText: hintText.tr,
      onChanged: onChanged,
      onSaved: onSubmitted,
      onTap: onTap,
      onEditingComplete: onEditingComplete,
      prefixWidget: Image.asset(
        "assets/images/ic_search.png",
        width: 14.w,
        height: 14.w,
      ).addPadding(const EdgeInsets.only(left: 14, right: 8)),
      // titleWidth: ,
      title: "",
      titleWidth: 0,
      spacing: 0,
      subTitleTextAlign: TextAlign.start,
      type: type ?? TextFormFieldWidgetType.edit,
      showCleanButton: true,
      subTitleStyle: TextStyle(color: const Color(0xFF212121), fontSize: 12.sp),
      hintTextStyle: TextStyle(
          fontSize: 12.sp,
          // color: const Color(0xFF888888),
          color: AppColor.textColor1,
          fontWeight: FontWeight.w500),
      inputBorder: TextFormFiledInputBorder.none,
      showArrowIcon: showArrowIcon ?? true,
    ).addContainer(
        height: height,
        color: bgColor ??  Colors.white,
        width: double.infinity,
        // margin: padding ?? const EdgeInsets.symmetric(horizontal: 15),
        border: AppStyle.defaultBorder(),
        padding: const EdgeInsets.only(right: 5));
  }

  static Widget getTextFiled({
    TextEditingController? controller,
    FormFieldSetter<String>? onSubmitted,
    ValueChanged<String>? onChanged,
    Color? bgColor,
    String hintText = "请输入",
    EdgeInsetsGeometry? padding,
    bool? autofocus,
    bool? enabled,
    GestureTapCallback? onTap,
    bool? isChoose = false,
    Widget? prefixWidget,
    Widget? suffixWidget,
    String? title,
    double? titleWidth,
    TextInputType? keyboardType,
    TextFiledEnum? type,
    List<TextInputFormatter>? inputFormatters,
    String? subtitle,
  }) {
    if (type == TextFiledEnum.phone) {
      keyboardType = TextInputType.number;
      inputFormatters = [LengthLimitingTextInputFormatter(11)];
    } else if (type == TextFiledEnum.authCode) {
      keyboardType = TextInputType.number;
      inputFormatters = [LengthLimitingTextInputFormatter(6)];
    }
    return TextFormFieldWidget(
      autofocus: autofocus,
      controller: controller,
      enabled: enabled ?? true,
      hintText: hintText,
      onChanged: onChanged,
      onSaved: onSubmitted,
      onTap: onTap,
      prefixWidget: prefixWidget,
      title: title,
      titleWidth: title != null ? 76 : titleWidth,
      spacing: 0,
      subTitleTextAlign: TextAlign.start,
      type: isChoose!
          ? TextFormFieldWidgetType.choose
          : TextFormFieldWidgetType.edit,
      suffixWidget: suffixWidget,
      showCleanButton: true,
      subTitleStyle: TextStyle(color: const Color(0xFF212121), fontSize: 14.sp),
      titleStyle: TextStyle(color: const Color(0xFF212121), fontSize: 14.sp),
      hintTextStyle: TextStyle(
        fontSize: 14.sp,
        color: AppColor.textColor1,
      ),
      keyboardType: keyboardType,
      inputFormatters: inputFormatters,
      subTitle: subtitle,
    ).addContainer(
        color: Colors.transparent,
        radius: 24.w,
        margin: padding ?? EdgeInsets.symmetric(horizontal: 32));
  }

  static Future<XFile?> showImagePicker(
      {Function(XFile? file)? callBack}) async {
    var resultFile = await showCupertinoModalPopup<XFile?>(
        context: Get.context!,
        builder: (context) {
          return SafeArea(
            top: false,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                AppButton.fullBtn(() async {
                  var res = await _uploadImage(0);
                  callBack?.call(res);
                  Get.back(result: res);
                }, Text("拍照",style: AppStyle.textStyle,), bgColor: Colors.transparent),
                Divider(
                  color: AppColor.dividerColor,
                  thickness: 0.5,
                  height: 0.5,
                ),
                AppButton.fullBtn(() async {
                  var res = await _uploadImage(1);
                  callBack?.call(res);
                  Get.back(result: res);
                }, Text("相册",style: AppStyle.textStyle,), bgColor: Colors.transparent),
                Divider(
                  color: AppColor.dividerColor,
                  thickness: 0.5,
                  height: 0.5,
                ),
                AppButton.fullBtn(() {
                  Get.back();
                }, Text("取消", style: TextStyle(color: Colors.red)),
                    bgColor: Colors.transparent)
              ],
            ),
          ).addContainer(color: Colors.white);
        });
    return resultFile;
  }

  static Future<XFile?> _uploadImage(int type) async {
    var state = await WidgetUtil.showPermission(type == 0? Permission.camera: Permission.storage);
    if(!state) return null;
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(
        source: type == 0 ? ImageSource.camera : ImageSource.gallery,
        imageQuality: 80,
        maxHeight: 200,
        maxWidth: 200
    );
    return image;
  }

  static Widget checkBoxProtoCol(bool value, String title,
      {Function(bool?)? onTap,
      bool? isRadio = false,
      TextStyle? textStyle,
      List<String>? protocols,
      List<Function>? functions,
      List<String>? protocolUrls,
      List<String>? protocolTitles
      }) {
    // List<TextSpan> children = [ TextSpan(
    //   text: title,
    // )];
    // if (protocols != null && protocolUrls != null) {
    //   for(int i = 0; i < protocols.length;i ++){
    //
    //     children.add(TextSpan(
    //         text: protocols[i],
    //         style: TextStyle(
    //             fontSize: textStyle?.fontSize,
    //             color: textStyle?.color,
    //             decoration: TextDecoration.underline,
    //             decorationColor: AppColor.red),recognizer: TapGestureRecognizer()
    //       ..onTap = () {
    //         Get.to(() =>  WebViewWidget(
    //           url: protocolUrls[i],
    //           title: protocolTitles?[i],
    //           titleChange: false,
    //         ));
    //       }));
    //   }
    // }
    // String target = protocols![0];
    // // 找到目标字符串的起始位置
    // int startIndex = title.indexOf(target);
    // // 计算结束位置
    // // int endIndex = startIndex + target.length;
    // String result = title.substring(0, startIndex);
    return Row(
      children: [
        RectangleCheckBox(
          //自定义矩形的checkbox
          size: 30.w,
          // checkedColor: Colors.orange,
          checkedWidget:
          Icon(
            Icons.check_box_outlined,
            color: AppColor.primaryColor,
            size: 12.w,
          ),
          uncheckedWidget:   Icon(
            Icons.check_box_outline_blank,
            color: AppColor.primaryColor,
            size: 12.w,
          ),
          isChecked: value,
          checkedColor: Colors.transparent,
          borderColor: Colors.transparent,
          uncheckedColor: Colors.transparent,
          disabledColor: Colors.transparent,
          onTap: (newValue) {
            onTap?.call(newValue);
          },
        ),
        SizedBox(
          width: 3,
        ),
          Text.rich(
            style: TextStyle(fontSize: 12.sp, color: AppColor.textColor),
            TextSpan(
              children: [
                TextSpan(text: "privacy_checkout".tr),
                TextSpan(
                text: "user_privacy".tr,
                style: TextStyle(
                    fontSize: textStyle?.fontSize,
                    color: textStyle?.color,
                    decoration: TextDecoration.underline,
                    decorationColor: AppColor.textColor),recognizer: TapGestureRecognizer()
              ..onTap = () {
                Get.to(() =>  WebViewWidget(
                  url: protocolUrls?.first ?? "https://www.baidu.com",
                  title: protocolTitles?.first ?? "user_privacy".tr,
                  titleChange: false,
                ));
              })
              ],
            ),
          ).addExpand(),
      ],
    ).addGestureTap(() {
      onTap?.call(!value);
    });
  }

  static Widget getHeaderInfo(String title,Widget child,{double ? space}){
    return Column(crossAxisAlignment: CrossAxisAlignment.start,children: [
      Text(title,style: AppStyle.subtitleStyle,),
      SizedBox(height: space ?? 12.h,),
      child
    ],);
  }


  static Future<bool> showPermission(Permission permission,{bool? openSetting = true})async{
    if(Platform.isIOS){
      return true;
    }
    var des = "权限",name = "";

    switch(permission.value){
      case 1:
        des = "我们将获取您的拍照权限，以便于您能通过摄像头识别设备的二维码添加设备到app，使用拍照权限修改头像";
        name = "相机";
      case 3:
        des = "我们将获取您的位置信息，以便于您在商城预约服务的时候，我们能根据位置判断您是否可以预约该服务，若您不同意该权限，我们将无法为你开启预约服务功能。";
        name = "定位";
      case 9:
        des = "我们将获取您的相册权限，以便于您能通过相册选择照片修改头像。";
        name = "相册";
      case 15:
        des = "我们将获取您的相册权限，以便于您能通过相册选择照片修改头像。";
        name = "相册";
      case 17:
        des = "我们将获取您的推送权限，以便于物理设备的围栏报警或相关预警信息能及时的发送到您的手机上。";
        name = "推送";
      case 24:
        des = "我们将获取您的安装权限，以便于更新版本。";
        name = "安装";
    }

    final androidInfo = await DeviceInfoPlugin().androidInfo;
    if(androidInfo.version.sdkInt > 32 && permission.value == 15){
      permission = Permission.photos;
    }
    var status = await permission.status;
    if(status.isPermanentlyDenied){
      ///永久拒绝
      if(openSetting == true) {
        WidgetUtil.showDialog("未开启$name权限", des,() async {
          openAppSettings();
        }, okText: "去设置");
      }
      return false;
    }else if(status.isDenied){
      bool isHuaw = await isHuawei();
      if(UserData.permissionValues.value[permission.value.toString()] != null){
        if(openSetting == true) {
          WidgetUtil.showDialog("未开启$name权限", des,() async {
            var isOpen = await openAppSettings();
          }, okText: "去设置");
        }
        return false;
      }
      ///之前的判断
      if(!isHuaw && permission.value == 9){
        var status = await permission.request();
        return true;
      }

      ///拒绝
      var result = await Get.dialog<bool>(PermissionWidget(desc: des,permission: permission),barrierColor: Colors.transparent,barrierDismissible: false);
      return result ?? false;

    }else if(status.isGranted){
      return true;
    }

    return false;
  }

  static Future<bool> isHuawei() async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    String brand = 'unknown';
    try {
      switch (Platform.operatingSystem) {
        case 'android':
          var androidInfo = await deviceInfo.androidInfo;
          brand = androidInfo.brand;
          break;
        case 'ios':
          var iosInfo = await deviceInfo.iosInfo;
          brand = iosInfo.utsname.machine;
          break;
        default:
          throw 'Unsupported platform';
      }
    } on PlatformException {
      brand = 'unknown';
    }

    return brand.toLowerCase() == 'huawei' || brand.toLowerCase() == 'huawei mengshuai';
  }
}





enum TextFiledEnum { authCode, phone, password }
